import { createRouter, createWebHistory } from 'vue-router'
import store from '@/store'
import StoreFrame from '../views/StoreFrame.vue'

const routes = [
  // 内容
  {
    path: '/',
    name: 'StoreFrame',
    component: StoreFrame,
    children: [
      {
        path: '/StoreMain',
        name: 'StoreMain',
        component: () => import(/* webpackChunkName: "StoreMain" */ '../views/StoreMain.vue')
      },
      // 商品分类
      {
        path: '/GoodsCategory',
        name: 'GoodsCategory',
        component: () => import(/* webpackChunkName: "GoodsCategory" */ '../views/GoodsCategory.vue')
      },
      // 个人中心
      {
        path: '/PersonalCenter',
        name: 'PersonalCenter',
        component: () => import(/* webpackChunkName: "PersonalCenter" */ '../views/PersonalCenter.vue')
      },
      // 购物车
      {
        path: '/ShoppingCart',
        name: 'ShoppingCart',
        component: () => import(/* webpackChunkName: "ShoppingCart" */ '../views/ShoppingCart.vue')
      },
      // 订单中心
      {
        path: '/OrderCenter',
        name: 'OrderCenter',
        component: () => import(/* webpackChunkName: "OrderCenter" */ '../views/OrderCenter.vue')
      },
      // 联系客服
      {
        path: '/ContactUs',
        name: 'ContactUs',
        component: () => import(/* webpackChunkName: "ContactUs" */ '../views/ContactUs.vue')
      },
      // 商品详情
      {
        path: '/GoodsDetail',
        name: 'GoodsDetail',
        component: () => import(/* webpackChunkName: "GoodsDetail" */ '../views/GoodsDetail.vue')
      },
      // 提交订单
      {
        path: '/SettleAccounts',
        name: 'SettleAccounts',
        component: () => import(/* webpackChunkName: "SettleAccounts" */ '../views/SettleAccounts.vue')
      },
    ]
  },
  // 登录
  {
    path: '/login',
    name: 'login',
    component: () => import(/* webpackChunkName: "login" */ '../views/login.vue')
  },
  // 注册
  {
    path: '/register',
    name: 'register',
    component: () => import(/* webpackChunkName: "register" */ '../views/register.vue')
  },
]


const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// 路由拦截(守卫)，判断是否登录
router.beforeEach((to, from, next) => {
  // 保存用户信息，防止页面刷新用户数据消失
  if (sessionStorage.shopToken != null) {
    let userInfo = JSON.parse(sessionStorage.shopToken)
    store.dispatch('setUserInfo', userInfo)
  }
  // console.log('beeforeEach:', to.name, from.name);
  let item = sessionStorage.getItem("shopToken");
  item = JSON.parse(item)
  // console.log(item);
  if (to.path === '/') {//重定向到首页
    next({
      path: '/StoreMain'
    })
  } else {
    if (to.path === '/login' || to.path === '/register' || to.path === '/StoreMain') {
      next()
    } else {
      if (item == null) {
        next({
          path: '/login'
        })
      } else {
        next()
      }
    }
  }
})
export default router
